package com.tanhua.dubbo.Api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author 刘付磊
 * @date 2021/11/22 0022
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean updateLocation(Long userId, Double longitude, Double latitude, String address) {
        //1.根据用户id查询用户信息
        try {
            Query query  = Query.query(Criteria.where("userId").is(userId));
            UserLocation one = mongoTemplate.findOne(query, UserLocation.class);
            if(ObjectUtil.isEmpty(one)){
                UserLocation location = new UserLocation();
                location.setUserId(userId);
                location.setLocation(new GeoJsonPoint(longitude,latitude));
                location.setAddress(address);
                location.setCreated(System.currentTimeMillis());
                location.setUpdated(System.currentTimeMillis());
                location.setLastUpdated(System.currentTimeMillis());
                mongoTemplate.save(location);
            }else {
                Update update = Update.update("location",new GeoJsonPoint(longitude,latitude)).
                        set("updated",System.currentTimeMillis()).set("lastUpdated",one.getUpdated());
                mongoTemplate.updateFirst(query,update,UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Long> queryNearUser(Long userId, Double aDouble) {
        //1.查询当前用户的位置
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation one = mongoTemplate.findOne(query, UserLocation.class);
        if (ObjectUtil.isEmpty(one)){
            return null;
        }
        GeoJsonPoint location = one.getLocation();//原点
        Distance Distance = new Distance(aDouble/1000,Metrics.KILOMETERS);//半径
        Circle Circle = new Circle(location,Distance);
        Query query1 = Query.query(Criteria.where("location").withinSphere(Circle));
        List<UserLocation> Locations = mongoTemplate.find(query1, UserLocation.class);
        return CollUtil.getFieldValues(Locations,"userId",Long.class);
    }
}
